<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="roleList.rows"
              @selection-change="selectedChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="90">
      </el-table-column>
      <el-table-column prop="name" label="权限名" width="240">
      </el-table-column>
      <el-table-column prop="sn" label="SN" width="300">
      </el-table-column>
      <el-table-column label="操作" >
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="handlePermission(scope.$index, scope.row)">权限设置</el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.selected.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="roleList.total"
          style="float:right;">
      </el-pagination>
    </el-col>
    <el-dialog title="新增/保存"
               :visible.sync="formVisible"
               :close-on-click-modal="false">
      <el-form :model="roleForm" label-width="80px" :rules="formRules" ref="editForm">
        <el-form-item label="角色名" prop="name">
          <el-input v-model="roleForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="SN" prop="sn">
          <el-input v-model="roleForm.sn" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="formVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="权限设置"
               :visible.sync="permissionFormVisible"
               :close-on-click-modal="false">
      <el-form :model="rolePermission" label-width="80px" :rules="rolePermission" ref="saveForm">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div class="checkbox-table" v-for="(parent,indexKey) in permissionTree" :key="parent.sn">
          <template>
            <!--一级权限-->
            <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                         v-model='rolePermission.permissionSns'
                         :label="parent.sn"
                         @change='handleCheck(1,indexKey)'
                         :indeterminate="firstIndeterminate"
            >
              {{parent.name}}
            </el-checkbox>
            <div style="margin-bottom: 20px;">
              <!--二级权限-->
              <div v-for="c in parent.children" class="line-check" :key="c.sn"
                   style="display: inline-block; margin-left: 20px;margin-bottom: 20px;" >
                <el-checkbox class="check2" @change='handleCheck(2,indexKey)'
                             v-model="rolePermission.permissionSns" :label="c.sn">
                  {{c.name}}
                </el-checkbox>
              </div>
            </div>
          </template>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="permissionFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="savePermissionSubmit">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  mounted() {
    this.getRole()
  },
  data(){
    return{
      firstIndeterminate:false,
      formRules:{
        name: [
          {required: true, message: '请输入活动名称', trigger: 'blur'},
        ],
        sn: [
          {required: true, message: '请输入唯一标识', trigger: 'blur'}
        ]
      },
      query:{
        keyword:"",
        currentPage:1,
        pageSize:10
      },
      roleList:{
        rows:[],
        total:0
      },
      roleForm:{
        name:"",
        sn:""
      },
      permissionFormVisible:false,
      selected:[],
      formVisible:false,
      isIndeterminate:false,
      checkAll:false,
      permissionTree:[],
      rolePermission: {
        roleId:null,
        permissionSns:[],
      },
      allPermissionSns:[]
    }
  },
  methods:{
    savePermissionSubmit(){
      console.log(this.rolePermission);
      this.$confirm('确认提交吗？', '提示', {})
          .then(() => {
            // 调用后端接口-axios
            this.$http.put("/role/permission", this.rolePermission)
                .then(result => {
                  // 获取后端返回的结果
                  result = result.data; // {success:true,message:""}
                  if (result.success) {
                    this.$message({message: "保存成功!", type: 'success'});
                    // 关闭弹框
                    this.permissionFormVisible = false;
                  } else {
                    this.$message({message: result.message, type: 'error'});
                  }
                })
                .catch(() => {
                  this.$message({message: "网络异常,请检查网络!", type: 'error'});
                })
          })
          .catch(() => {
            this.$message({message: "已取消", type: 'info'});
          });
    },
    handleCheck(type,a = 0){
      let indexOf = this.rolePermission.permissionSns.indexOf(this.permissionTree[a].sn);
      let checked = indexOf > -1;
      if (type === 2) { // 二级权限点击
        let index = 0;  //
        this.permissionTree[a].children.map(item => {
          // 已选中的权限列表中，是否包含当前一级权限下的某个子权限
          if (this.rolePermission.permissionSns.indexOf(item.sn) > -1) {
            index += 1;
          }
        })
        if (index > 0) {  // 已选中的权限列表中，包含当前一级权限下的某个子权限
          // 如果下面的子权限被选中,但是一级权限没被选中,那么就将一级权限选中
          if (!checked) {  // 已选中的权限列表中，没有当前一级权限，则添加到已选中的权限列表中
            this.rolePermission.permissionSns.push(this.permissionTree[a].sn);
          }
        } else {  // 已选中的权限列表中，不包含当前一级权限下的任何子权限
          // 如果子权限一个都没有被选中,但是一级权限被选中了,那么就要将一级权限取消选中
          if (checked) {// 已选中的权限列表中，有当前一级权限，则删除
            this.rolePermission.permissionSns.splice(indexOf, 1);
          }
        }
      } else {  // 一级权限点击
        if (checked) { // 已选中的权限中，包含当前一级权限，则将该一级权限下所有的子权限选中
          this.permissionTree[a].children.map(item => {
            if (this.rolePermission.permissionSns.findIndex((n) => n === item.sn) < 0) {
              this.rolePermission.permissionSns.push(item.sn)
            }
          })
        } else {
          // 已选中的权限中，不包含当前一级权限，则将该一级权限下所有的子权限移除
          this.permissionTree[a].children.map(item => {
            if (this.rolePermission.permissionSns.findIndex((n) => n === item.sn) > -1) {
              this.rolePermission.permissionSns.splice(this.rolePermission.permissionSns.findIndex((n) => n === item.sn), 1);
            }
          })
        }
      }
      // 获取当前已选中的权限的长度
      let checkedCount = this.rolePermission.permissionSns.length;
      // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
      this.checkAll = checkedCount === this.allPermissionSns.length;
      // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPermissionSns.length;
    },
    handleCheck2(type,a = 0){
      // 判断当前一级权限是否被选中
      let indexOf = this.rolePermission.permissionSns.indexOf(this.permissionTree[a].sn);
      let chosen = indexOf > -1
      if (type === 2){
        let index = 0
        this.permissionTree[a].children.map(item => {
          // this.rolePermission.permissionSns.indexOf(item.sn) 获取当前点击的二级权限是否被选中
          if (this.rolePermission.permissionSns.indexOf(item.sn) > -1) {
            // 获取一级权限下选中的二级权限的个数
            index += 1
          }
          // 判断当前一级权限下的二级权限是否被选择
          if (index > 0 && index < this.permissionTree[a].length){
            this.firstIndeterminate = true
            if (!chosen) {
              // 如果一级权限未被选中，当前一级权限下的二级权限选中个数 > 0 ,就将当前一级权限放进form表单接收的数组中
              this.rolePermission.permissionSns.push(this.permissionTree[a].sn)
            }
          } else if (index === this.permissionTree[a].length){
            this.firstIndeterminate = false
          } else {
            if (chosen) {
              this.rolePermission.permissionSns.splice(indexOf,1)
            }
          }
        })
      } else {
        if (chosen) {
          this.permissionTree[a].children.map(item => {
            if (this.rolePermission.permissionSns.findIndex(item.sn) < 0){
              this.rolePermission.permissionSns.push(item.sn)
            }
          })
        } else {
          this.rolePermission[a].children.map(item => {
            if (this.rolePermission.permissionSns.findIndex(item.sn) > -1){
              this.rolePermission.permissionSns.splice(this.rolePermission.permissionSns.findIndex(item.sn),1)
            }
          })
        }
      }
      let snLength = this.rolePermission.permissionSns.length;
      this.checkAll = snLength === this.allPermissionSns.length
      this.isIndeterminate = snLength > 0 && snLength < this.allPermissionSns.length
    },
    handleCheckAllChange(val){
      this.rolePermission.permissionSns = val ? this.allPermissionSns : [];
      console.log(this.allPermissionSns)
      this.isIndeterminate = false;
    },
    handlePermission(index,row){
      this.permissionFormVisible = true
      this.rolePermission.roleId = row.id
      this.getPermissionTree()
      this.getRolePermission(row.id)
    },
    getRolePermission(roleId){
      this.$http.get("/role/permission/"+roleId)
          .then(result => {
            result = result.data
            if (result.success) {
              this.rolePermission.permissionSns = result.data
              // 获取当前已选中的权限的长度
              let checkedCount = this.rolePermission.permissionSns.length;
              // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
              this.checkAll = checkedCount === this.allPermissionSns.length;
              // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
              this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPermissionSns.length;
            } else {
              this.$message({message: result.message, type: 'error'});
            }
          })
          .catch(() => {
            this.$message({message: "网络异常,请检查网络!", type: 'error'});
          });
    },
    getPermissionTree(){
      this.allPermissionSns = []
      this.$http.get("/permission/tree")
      .then(result => {
        result = result.data
        if (result.success){
          this.permissionTree = result.data
          for (let i = 0; i <this.permissionTree.length; i++) {
            let parent = this.permissionTree[i];
            this.allPermissionSns.push(parent.sn)
            for (let j = 0; j < parent.children.length; j++) {
              this.allPermissionSns.push(parent.children[j].sn)
            }
          }
        } else {
          this.$message({message: result.message, type: 'error'});
        }
      })
      .catch(() => {
        this.$message({message: "网络异常,请检查网络!", type: 'error'});
      })
    },
    handleAdd(){
      this.roleForm = {
        name:"",
        sn:""
      }
      this.formVisible = true
    },
    saveSubmit(){
      this.$confirm('确认提交吗？', '提示', {})
          .then(() => {
            // 调用后端接口-axios
            this.$http.put("/role", this.roleForm)
                .then(result => {
                  // 获取后端返回的结果
                  result = result.data; // {success:true,message:""}
                  if (result.success) {
                    this.$message({message: "保存成功!", type: 'success'});
                    // 关闭弹框
                    this.formVisible = false;
                    this.roleForm = {
                      name: "",
                      sn: ""
                    }
                    this.query.currentPage = 1;
                    this.getRole();
                  } else {
                    this.$message({message: result.message, type: 'error'});
                  }
                })
                .catch(() => {
                  this.$message({message: "网络异常,请检查网络!", type: 'error'});
                })
          })
          .catch(() => {
            this.$message({message: "已取消", type: 'info'});
          });
    },
    batchRemove(){
      let ids = this.selected.map(item =>item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 2 调后端的删除接口
        this.$http.patch("/role", ids)
            .then(result => {
              result = result.data; // {success:true,message:""}
              if (result.success) {
                // 提示"删除成功"
                this.$message({ message: "删除成功!", type: 'success' });
                // 删除成功以后,要重新查询数据,并且要从第一页开始进行查询
                this.query.currentPage = 1;
                // 调用查询方法
                this.getRole();
                // this.search();
              } else {
                this.$message({ message: result.message, type: 'error' });
              }
            })
            .catch(result => {
              this.$message({ message: "网络异常,请检查网络!", type: 'error' });
            })
      }).catch(() => {
        this.$message({ message: '已取消删除!', type: 'info' });
      });
    },
    handleEdit(index,row){
      this.roleForm = row
      this.formVisible = true
    },
    handleDel(index,row){
      this.$confirm('确认删除吗？', '提示', {type: 'warning'})
          .then(() => {
            let id = row.id
            this.$http.delete("/role/" + id)
                .then(result =>{
                  result = result.data
                  if (result.success){
                    this.$message({ message: "删除成功!", type: 'success' });
                    this.query.currentPage = 1
                    this.getRole()
                  } else {
                    this.$message({ message: result.message, type: 'error' });
                  }
                })
                .catch(result => {
                  this.$message({message: '删除失败!', type: 'error'});
                })
          }).catch(() => {
        this.$message({message: '已取消删除!', type: 'info'});
      });
    },
    selectedChange: function (selected) {
      this.selected = selected;
    },
    search(){
      this.query.currentPage = 1
      this.getRole()
    },
    handleSizeChange(val){
      this.query.pageSize = val;
      this.query.currentPage = 1;
      this.getRole()
    },
    handleCurrentChange(val){
      this.query.currentPage = val
      this.getRole()
    },
    getRole(){
      this.$http.post("/role",this.query)
      .then(result =>{
        result = result.data
        if (result.success){
          this.roleList = result.data
        } else{
          this.$message({
            message: result.data.message,
            type: 'error'
          });
        }

      })
      .catch(() =>{
        this.$message({
          message: '网络异常',
          type: 'error'
        });
      })
    }
  }
}
</script>

<style scoped>

</style>